#!/bin/bash
# @author:      tanj
# @mail:        tanjiong@sjgtw.com
# @create_date: 2021-11-12
# @update_time:      2021-11-17 02:27:12
# @version:     1.0
# @description: Starts and stops the App.
#
######### Pre-setup for running the script #########
SCRIPT_NAME=${0##*/}
#File working directory
SCRIPT_PATH=$(dirname $(readlink -f $0) || pwd)
WORK_PATH=$( cd ${SCRIPT_PATH}/.. ;pwd)
SCRIPT_PATH=${SCRIPT_PATH}/$SCRIPT_NAME
#Add execute permission to file
#chmod +x ${SCRIPT_PATH}
#The time when the file was last updated
#LAST_UPDATE_TIME=$(stat -c %Y ${SCRIPT_PATH})
#Time formatting
#FORMAT_LAST_UPDATE_TIME=$(date '+%Y-%m-%d %H:%M:%S' -d @${LAST_UPDATE_TIME})
#Replace the update time of the file
#sed -i  "5c# @update_time:      $FORMAT_LAST_UPDATE_TIME"  ${SCRIPT_PATH}
#Print the process ID of the script
PID=$$
#The program runs for the specified user
#RUNNING_USER=root
#The project name
APP_NAME=${WORK_PATH##*/}
#Run the JAR package file
JAR_FILE=$(ls -t ${WORK_PATH} |grep '.jar$' |head -1)
#JAR_PATH=$(cd ${WORK_PATH}/lib)
#########
#
#
######### Definition of color #########
function color_definition(){
    RC='\033[1;31m'
    GC='\033[1;32m'
    BC='\033[1;34m'
    YC='\033[1;33m'
    EC='\033[0m'
}
color_definition
#########
#
#
######### Set the log output format #########
##The current time
function now_time(){
   current_date=$(date '+%Y-%m-%d')
   current_time=$(date '+%Y-%m-%d %H:%M:%S+%N')
}
##The error log
function errorlog() {
     now_time
     # shellcheck disable=SC2145
     echo -e "[$current_time] ${RC} [ERROR]${EC} $@" 1>&2
}
##The info log
function infolog() {
    now_time
    # shellcheck disable=SC2145
    echo -e "[$current_time] ${GC} [INFO]${EC} $@" 1>&2
}
##The warn log
function warnlog() {
    now_time
    # shellcheck disable=SC2145
    echo -e "[$current_time] ${YC} [WARN]${EC} $@" 1>&2
}
##Creating a log file
function mkdir_log(){
    now_time
    LOG_PATH=${WORK_PATH}/logs
    readonly LOG_PATH
    uuid=$(cat /proc/sys/kernel/random/uuid)
    LOG_FILE=$LOG_PATH/${current_date}-${uuid}
    if [ ! -d $LOG_PATH ];then
        mkdir -p $LOG_PATH
    else
        ##Save logs generated in recent days
        #del_log_day_num=30
        if [ ! -n "$del_log_day_num" ];then
            infolog "Refer to the Settings after line $LINENO to see if you want to clean up log files" >> $LOG_FILE
        else
            ##Clear logs generated by the project
            infolog "find ${WORK_PATH}/logs/ -mindepth 0 -type d -mtime +${del_log_day_num} -exec rm -f {};" >> $LOG_FILE
            find ${WORK_PATH}/logs/ -mindepth 0 -type d -mtime +${del_log_day_num} -exec rm -f {};
        fi
    fi
    infolog "The program run log file is $LOG_FILE"
    infolog "PID of this script: ${PID}" | tee -a $LOG_FILE
}
mkdir_log
#########
#
#
######### Program running environment check #########
##cpu
#
##memory
#
##disk
#
##network
#
##java
#echo $JAVA_HOME
#java -version
##python
#echo $PYTHON_HOME
#python -V
#########
#
#
######### Program running environment Settings #########
#
#
#JMX
#JMX="-Djava.rmi.server.hostname=127.0.0.1 " \
#" -Dcom.sun.management.jmxremote " \
#" -Dcom.sun.management.jmxremote.port=1091 " \
#" -Dcom.sun.management.jmxremote.ssl=false " \
#" -Dcom.sun.management.jmxremote.authenticate=false "
#export JAVA_OPTS=${JMX}
#JVM
#JVM_OPTS="-XX:+PrintHeapAtGC -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationStoppedTime "\
#"-XX:+PrintGCTaskTimeStamps -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+DisableExplicitGC "
JVM_OPTS="-XX:+HeapDumpOnOutOfMemoryError -verbose:gc "\
"-Xloggc:${WORK_PATH}/logs/gc.%t.log -XX:HeapDumpPath=${WORK_PATH}/tmp "\
"-Xms1024m -Xmx1024m -Xmn256m -Xss256k -Xdebug -Xrunjdwp:transport=dt_socket,suspend=n,server=y,address=5555 "
#
#
#########
#
#
######### Script running body  #########
# check the RUNNING PID of the project
# Globals:
#   JAR_FILE
# Arguments:
#   None
# Returns:
#   jar_pid
is_exist(){
    jar_pid=$(ps -ef |grep $JAR_FILE |grep -v grep |awk '{print $2}')
    infolog "pid==${jar_pid}"
    #如果不存在返回1，存在返回0
    if [ -z "${jar_pid}" ]; then
       return 1
    else
       return 0
    fi
}
# running the project
# Globals:
#   JVM_OPTS
#   JAR_FILE
#   LOG_FILE
#   RUNNING_USER
# Arguments:
#   jar_pid
# Returns:
#   JAVA_CMD
start(){
    infolog "*********check is_exist in first*****"
    is_exist
    # shellcheck disable=SC2181
    if [ "$?" -eq "0" ]; then
        infolog "${APP_NAME} is already running. pid=${jar_pid} ."
    else
        infolog "${APP_NAME} is not running and pid is null ."
        JAVA_CMD="cd ${WORK_PATH} ; java -jar $JVM_OPTS ${JAR_FILE} "
        infolog ${JAVA_CMD} |tee -a $LOG_FILE
        cd ${WORK_PATH} ; java -jar $JVM_OPTS ${JAR_FILE}
        infolog "---------------------------------"
        infolog "启动完成，按CTRL+C退出日志界面即可>>>>>"
        infolog "---------------------------------"
#        sleep 2s
#        tail -f ${LOG_PATH}/${APP_NAME}.log
    fi
}
#View the running status of the project
# Globals:
#   None
# Arguments:
#   jar_pid
# Returns:
#   None
status(){
    is_exist
    if [ "$?" -eq "0" ]; then
        infolog "${APP_NAME} is running. Pid is ${jar_pid}"
    else
        infolog "${APP_NAME} is not running."
    fi
}
#Stop running project
# Globals:
#   None
# Arguments:
#   jar_pid
# Returns:
#   None
stop(){
    is_exist
    if [ "$?" -eq "0" ]; then
        infolog "kill -9 $jar_pid"
        #kill -9 $jar_pid
        kill $jar_pid
    else
        infolog "${APP_NAME} is not running"
    fi
}
#Rerun the project
restart(){
    stop
    sleep 1s
    start
}
#使用说明，用来提示输入参数
usage() {
        infolog "Usage: sh ${SCRIPT_NAME} [start|stop|restart|status]"
        exit 1
}
#The first parameter constraint
case $1 in
          "start") start;;
          "stop")  stop;;
          "restart")  restart;;
          "status")  status;;
              *)  usage  ;;
esac
#########
